//
//  LZYViewController.h
//  Supervisor
//
//  Created by 小宇 on 2017/5/10.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "LZYNetworkHelper.h"
#import "SVProgressHUD.h"
#import "MJRefresh.h"
#import "User.h"
#import "UIView+LZYEmptyView.h"
@interface LZYBaseViewController ()<UITableViewDelegate,UITableViewDataSource>
{

    CGFloat navigationY;
    CGFloat navBarY;
    CGFloat verticalY;
    BOOL _isShowMenu;
}
@property CGFloat original_height;
@property (nonatomic,strong)NSDictionary *loadparameterDic;
@property (nonatomic,strong)NSMutableDictionary *parameterDic;
@property (nonatomic,strong)UITableView *tableView;
@end

@implementation LZYBaseViewController

-(id)init
{
    if (self= [super init]) {
        navBarY = 0;
        navigationY = 0;
    }
    return self;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = BackgroundColor;
    self.extendedLayoutIncludesOpaqueBars=YES;
    [self getNetWorkState];
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)] ){
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    if ([self respondsToSelector:@selector(set_tableViewWithFrame)]) {
        UITableView *tableView = [self set_tableViewWithFrame];
        [self set_tableView:tableView];
    }
    if ([self respondsToSelector:@selector(setHeaderAndFooterRefresh)]) {
        if ([self setHeaderAndFooterRefresh]) {
            [self HeaderAndFooterRefresh];
        }
    }
    if ([self respondsToSelector:@selector(sendParameterWithRefreshGet)]) {
        self.loadparameterDic = [self sendParameterWithRefreshGet];
        [self reloadDataWithRefreshGet];
    }
    if ([self respondsToSelector:@selector(sendParameterWithGet)]) {
        self.loadparameterDic = [self sendParameterWithGet];
        [self reloadDataWithGet];
    }
    if ([self respondsToSelector:@selector(navBackgroundImage)]) {
        UIImage *bgimage = [self navBackgroundImage];
        [self setNavigationBack:bgimage];
    }else{
        UIImage *bgimage = [UIImage imageWithColor:MainColor];
        [self setNavigationBack:bgimage];
    }
    if ([self respondsToSelector:@selector(setNavTitle)]) {
        self.navigationItem.title = [self setNavTitle];
    }
    if ([self respondsToSelector:@selector(setTitle)]) {
        NSMutableAttributedString *titleAttri = [self setTitle];
        [self set_Title:titleAttri];
    }
    if (![self leftButton]) {
             [self configLeftBaritemWithImage];
    }
    if (![self rightButton]) {
        [self configRightBaritemWithImage];
    }
}

- (void)getNetWorkState{
    [LZYNetworkHelper startMonitoringNetwork];
    [LZYNetworkHelper networkStatusWithBlock:^(LZYNetworkStatus status) {
        switch (status) {
            case LZYNetworkStatusUnknown:
                [self.tableView hideErrorPageView];
            case LZYNetworkStatusNotReachable: {
                [self.tableView showErrorPageView];
                [self.tableView configReloadAction:^{
                    [LZYNetworkHelper startMonitoringNetwork];
                }];
                break;}
            case LZYNetworkStatusReachableViaWWAN:
                [self.tableView hideErrorPageView];
                break;
            case LZYNetworkStatusReachableViaWiFi: {
                [self.tableView hideErrorPageView];
                break;
            }
        }
    }];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    UIColor *backgroundColor =  MainColor;
    UIImage *bgimage = [UIImage imageWithColor:backgroundColor];
    [self.navigationController.navigationBar setBackgroundImage:bgimage forBarMetrics:UIBarMetricsDefault];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    if ([self respondsToSelector:@selector(hideNavigationBottomLine)]) {
        if ([self hideNavigationBottomLine]) {
            blackLineImageView.hidden = YES;
        }
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)setNavigationBack:(UIImage*)image
{
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:image ];
    [self.navigationController.navigationBar setShadowImage:image];
}

#pragma mark --- NORMAl

-(void)set_Title:(NSMutableAttributedString *)title
{
    UILabel *navTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 120, 44)];
    navTitleLabel.numberOfLines=0;
    [navTitleLabel setAttributedText:title];
    navTitleLabel.textAlignment = NSTextAlignmentCenter;
    navTitleLabel.backgroundColor = [UIColor clearColor];
    navTitleLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleClick:)];
    [navTitleLabel addGestureRecognizer:tap];
    self.navigationItem.titleView = navTitleLabel;
}

- (void)set_tableView:(UITableView *)tableView{
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.mj_footer.automaticallyHidden = YES;
    self.tableView.backgroundColor = BackgroundColor;
    self.tableView = tableView;
    [self.view addSubview:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}


- (void)HeaderAndFooterRefresh{
    LZYWeakSelf(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself loadDataRefresh];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakself loadMoreData];
    }];
}

- (void)loadMoreData{
    [self.parameterDic setObject:@([[self.parameterDic objectForKey:@"pageNo"] integerValue] + 1) forKey:@"pageNo"];
    [LZYNetworkHelper GET:self.loadparameterDic[@"url"] parameters:self.parameterDic success:^(id responseObject) {
        if ([responseObject count] < 10 && [responseObject count] >0) {
             [self.tableView.mj_footer endRefreshingWithNoMoreData];
             self.netWorkMoreBlock(responseObject);
        }else if([responseObject count] == 10){
            [self.tableView.mj_footer endRefreshing];
            self.netWorkMoreBlock(responseObject);
        }else if([responseObject count] == 0){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        
    }showHub:YES];
}

- (void)reloadDataWithGet{
    self.parameterDic = [[NSMutableDictionary alloc]initWithCapacity:5];
    if ([self.loadparameterDic.allKeys containsObject:@"parameterDic"]) {
        self.parameterDic = [[NSMutableDictionary alloc]initWithDictionary:self.loadparameterDic[@"parameterDic"]];
        [self.parameterDic setObject:[[User shareInstance] getUserAccessToken] forKey:@"accessToken"];
    }else{
        self.parameterDic = [[NSMutableDictionary alloc]initWithDictionary:self.loadparameterDic[@"parameterDic"]];
    }
    [self loadData];
}

- (void)reloadDataWithRefreshGet{
    self.parameterDic = [[NSMutableDictionary alloc]initWithCapacity:5];
    if ([self.loadparameterDic.allKeys containsObject:@"parameterDic"]) {
        self.parameterDic = [[NSMutableDictionary alloc]initWithDictionary:self.loadparameterDic[@"parameterDic"]];
        [self.parameterDic setObject:[[User shareInstance] getUserAccessToken] forKey:@"accessToken"];
    }else{
        self.parameterDic = [[NSMutableDictionary alloc]initWithDictionary:self.loadparameterDic[@"parameterDic"]];
    }
    [self loadDataRefresh];
}



- (void)loadDataRefresh{
    [self.parameterDic setObject:@(1) forKey:@"pageNo"];
    [LZYNetworkHelper GET:self.loadparameterDic[@"url"] parameters:self.parameterDic success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        self.netWorkBlock(responseObject);
    } failure:^(NSError *error) {
        [self.tableView showErrorPageView];
    }showHub:YES];
}

- (void)loadData{
    [LZYNetworkHelper GET:self.loadparameterDic[@"url"] parameters:self.parameterDic success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        self.netWorkBlock(responseObject);
    } failure:^(NSError *error) {
       [self.tableView showErrorPageView]; 
    }showHub:YES];
}

-(void)titleClick:(UIGestureRecognizer*)Tap
{
    UIView *view = Tap.view;
    if ([self respondsToSelector:@selector(title_click_event:)]) {
        [self title_click_event:view];
    }
}

#pragma mark -- left_item
-(void)configLeftBaritemWithImage
{
    if ([self respondsToSelector:@selector(set_leftBarButtonItemWithImage)]) {
        UIImage *image = [self set_leftBarButtonItemWithImage];
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self  action:@selector(left_click:)];
        self.navigationItem.backBarButtonItem = item;
    }
}

-(void)configRightBaritemWithImage
{
    if ([self respondsToSelector:@selector(set_rightBarButtonItemWithImage)]) {
        UIImage *image = [self set_rightBarButtonItemWithImage];
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self  action:@selector(right_click:)];
        self.navigationItem.rightBarButtonItem = item;
    }
}


#pragma mark -- left_button
-(BOOL)leftButton
{
    BOOL isleft =  [self respondsToSelector:@selector(set_leftButton)];
    if (isleft) {
        UIButton *leftbutton = [self set_leftButton];
        [leftbutton addTarget:self action:@selector(left_click:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
        self.navigationItem.leftBarButtonItem = item;
    }
    return isleft;
}

#pragma mark -- right_button
-(BOOL)rightButton
{
    BOOL isright = [self respondsToSelector:@selector(set_rightButton)];
    if (isright) {
        UIButton *right_button = [self set_rightButton];
        [right_button addTarget:self action:@selector(right_click:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:right_button];
        self.navigationItem.rightBarButtonItem = item;
    }
    return isright;
}


-(void)left_click:(id)sender
{
    if ([self respondsToSelector:@selector(left_button_event:)]) {
        [self left_button_event:sender];
    }
}

-(void)right_click:(id)sender
{
    if ([self respondsToSelector:@selector(right_button_event:)]) {
        [self right_button_event:sender];
    }
}

-(void)changeNavigationBarHeight:(CGFloat)offset
{
    [UIView animateWithDuration:0.3f animations:^{
        self.navigationController.navigationBar.frame  = CGRectMake(
                                                                    self.navigationController.navigationBar.frame.origin.x,
                                                                    navigationY,
                                                                    self.navigationController.navigationBar.frame.size.width,
                                                                    offset
                                                                    );
    }];
    
}

-(void)changeNavigationBarTranslationY:(CGFloat)translationY
{
    self.navigationController.navigationBar.transform = CGAffineTransformMakeTranslation(0, translationY);
}

//找查到Nav底部的黑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark 自定义代码

- (void)showNewStatusesMessage:(NSInteger) count
{
    // 1.创建一个UILabel
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:12];
    
    // 2.显示文字
    if (count) {
        label.text = [NSString stringWithFormat:@"共有%ld条下载数据,侧滑删除数据", count];
    } else {
        label.text = @"没有最新的数据";
    }
    
    // 3.设置背景
    label.backgroundColor = [UIColor colorWithRed:254/255.0  green:129/255.0 blue:0 alpha:1.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    
    // 4.设置frame
    label.width = self.view.frame.size.width;
    label.height = 35;
    label.top = 0;
    label.bottom = 0;
    
    // 5.添加到导航控制器的view
    [self.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    // 6.动画
    CGFloat duration = 0.75;
    //label.alpha = 0.0;
    [UIView animateWithDuration:duration animations:^{
        // 往下移动一个label的高度
        label.transform = CGAffineTransformMakeTranslation(0, label.frame.size.height);
        //view做同样的动作
        self.tableView.transform = CGAffineTransformMakeTranslation(0, label.frame.size.height);
        //label.alpha = 1.0;
    } completion:^(BOOL finished) { // 向下移动完毕
        
        // 延迟delay秒后，再执行动画
        CGFloat delay = 1.0;
        
        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            // 恢复到原来的位置
            label.transform = CGAffineTransformIdentity;
            //label.alpha = 0.0;
            self.tableView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
            // 删除控件
            [label removeFromSuperview];
        }];
    }];
}


- (void)showMessage:(NSString *) message
{
    // 1.创建一个UILabel
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:12];
    
    // 2.显示文字
    label.text = message;
    
    // 3.设置背景
    label.backgroundColor = [UIColor colorWithRed:254/255.0  green:129/255.0 blue:0 alpha:1.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    
    // 4.设置frame
    label.width = self.view.frame.size.width;
    label.height = 35;
    label.top = 0;
    label.bottom = 0;
    
    // 5.添加到导航控制器的view
    [self.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    // 6.动画
    CGFloat duration = 1.5;
    //label.alpha = 0.0;
    [UIView animateWithDuration:duration animations:^{
        // 往下移动一个label的高度
        label.transform = CGAffineTransformMakeTranslation(0, label.frame.size.height);
        //label.alpha = 1.0;
    } completion:^(BOOL finished) { // 向下移动完毕
        
        // 延迟delay秒后，再执行动画
        CGFloat delay = 1.0;
        
        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            // 恢复到原来的位置
            label.transform = CGAffineTransformIdentity;
            //label.alpha = 0.0;
            
        } completion:^(BOOL finished) {
            
            // 删除控件
            [label removeFromSuperview];
        }];
    }];
}

- (void)dealloc{
    self.tableView.delegate = nil;
}


@end
